import axios from "axios";
import qs from "qs";
import wx from "weixin-js-sdk";
import { Notify } from "vant";
import { checkWechatEnv } from "./index";

import router from "@/router/index";

// 请求超时
const TIMEOUT = 10000;
// 请求队列
const fetchQueue = {};
// 是否开启请求锁。
let fetchLock = true;
// 忽略请求锁接口列表
const LOCK_DISABLED_LIST = ["/app/seller/getUserInfo"];
const token = localStorage.getItem("heyjie-token");
// 创建axios实例
const fetch = axios.create({
  // baseURL: 'https://api.shwzfa.cn/',
  baseURL: location.href.includes("shwzfa.cn")
    ? "https://api.shwzfa.cn/"
    : "https://api.izjut.cn/",

  // 超时
  timeout: TIMEOUT,

  // 是否跨域携带cookie
  withCredentials: true,

  headers: token
    ? {
        "heyjie-token": token,
        "channel-source": "H5",
      }
    : {
        "channel-source": "H5",
        "heyjie-token": "",
      },
});

// 请求拦截器
fetch.interceptors.request.use(
  function(config) {
    // 小程序内设置token
    if (!!window.isMiniprogram && !!window.heyjie_token) {
      config.headers["heyjie-token"] = window.heyjie_token;
      // config.headers['heyjie-token'] = '36511db9-f748-4ee0-bea9-4d1a917d3fe9'
    }
    // REST风格接口
    for (const key in config.data) {
      if (key.indexOf("{") === 0) {
        config.url = config.url.replace(key, config.data[key]);
        delete config.data[key];
      }
    }
    // 去除没有值的属性
    // for (const key in config.data) {
    //   const val = config.data[key]
    //   if (val === undefined || val === '' || val == null) {
    //     delete config.data[key]
    //   }
    // }
    // get传参
    config.method === "get" &&
      (config.data = Object.assign(
        { _stamp: new Date().getTime() },
        config.data
      ));
    if (
      config.method === "get" &&
      config.data &&
      Object.keys(config.data).length !== 0
    ) {
      config.url += `?${qs.stringify(config.data)}`;
    }

    // 设置header-token 和 userid
    // const authInfoString = localStorage.getItem('auth-info')
    // const authInfo = authInfoString ? JSON.parse(authInfoString) : null
    // config.headers._mes_auth_token = config.headers._mes_auth_token || (authInfo ? authInfo.token : '')

    // application/x-www-form-urlencoded
    if (
      config.headers["Content-Type"] === "application/x-www-form-urlencoded"
    ) {
      config.data = qs.stringify(config.data);
    }

    // 特殊接口处理请求锁
    if (LOCK_DISABLED_LIST.includes(config.url)) {
      fetchLock = false;
    }

    // 请求锁
    // const lock =
    //   config.fetchLock !== undefined && config.fetchLock !== null
    //     ? config.fetchLock
    //     : fetchLock

    // if (lock) {
    //   // 如果有同个请求在队列中，则取消即将发送的请求
    //   if (fetchQueue[config.baseURL + config.url]) {
    //     config.cancelToken = new axios.CancelToken(c => {
    //       c('cancel')
    //     })
    //   } else {
    //     // 添加入请求队列
    //     fetchQueue[config.baseURL + config.url] = 1
    //   }
    // }

    /**
     * 在发送请求之前做些什么
     */
    return config;
  },
  function(error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加请求返回拦截器
fetch.interceptors.response.use(
  function(res) {
    // responseLock(res.config)
    // 是否有请求锁
    const lock =
      res.config.fetchLock !== undefined && res.config.fetchLock != null
        ? res.config.fetchLock
        : fetchLock;
    if (lock) {
      // 移除出请求队列
      delete fetchQueue[res.config.url];
    }

    const { data } = res;
    const code = +data.code;
    if (code === 0) {
      return data.data;
    } else {
      
      if (
        !res.config.url.includes("app/wechat/tokenAvailableNew") &&
        !res.config.url.includes("app/login/loginStatus") &&
        !res.config.url.includes("app/wechat/tokenAvailable") &&
        !res.config.url.includes("app/login/isLogin") &&
        code === 10001
      ) {
        checkWechatEnv((res) => {
          if (res === "miniprogram") {
            wx.miniProgram.navigateTo({
              url: "/pages/login/login?from=webpage",
              success: (res) => {
                // 通过eventChannel向被打开页面传送数据
                wx.miniProgram.postMessage({ data: { needlogin: true } });
              },
            });
          } else {
            // location.replace(`./inde.html${util.joinQueryString({
            //   redirectUrl: location.href
            // })}`)
            router.push("/login");
          }
        });
      }

      // 除了验证wx-token接口，其他都提示
      if (
        !res.config.url.includes("app/wechat/tokenAvailableNew") &&
        !res.config.url.includes("app/wechat/tokenAvailable") &&
        !res.config.url.includes("app/seller/apply") &&
        !res.config.url.includes("app/login/loginStatus") &&
        !res.config.url.includes("app/login/isLogin") &&
        !res.config.url.includes("app/share_redpacket/receive_red_packe")
      ) {
        // Toast.info(data.message, 2000)
        Notify({
          type: "danger",
          message: data.message,
        });
      }

      // 打印错误信息
      return Promise.reject(data);
    }
  },
  function(error) {
    if (error.config) {
      responseLock(error.config);
    }
    if (error.message !== "cancel" && !error.message.includes('openid') && !error.config.url.includes("/app/wechat/tokenAvailableNew")) {
      Notify({
        type: "danger",
        message: error.message,
      });
    }

    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

function responseLock(config) {
  // 移除出请求队列
  delete fetchQueue[config.baseURL + config.url];
}

export default fetch;
